public without sharing class EquipmentHandler {
    
    public static void setCombiEquipLink(List<Equipment__c> list_new, Map<Id, Equipment__c> map_old) {
        Set<Id> newCombiIds = new Set<Id>();
        Set<Id> oldCombiIds = new Set<Id>();
        for (Equipment__c e : list_new) {
            Equipment__c olde = null;
            if (map_old != null) olde = map_old.get(e.Id);
            // 新建
            if (olde == null) {
                if (e.CombinationForm__c != null) {
                    newCombiIds.add(e.CombinationForm__c);
                }
            }
            // 编辑
            else {
                System.debug('更新前'+olde);
                System.debug('更新后'+e);
                // 组合形式变了
                if (olde.CombinationForm__c != e.CombinationForm__c) {
                    if (e.CombinationForm__c != null) {
                        newCombiIds.add(e.CombinationForm__c);
                    }
                    if (olde.CombinationForm__c != null) {
                        oldCombiIds.add(olde.CombinationForm__c);
                    }
                } else {
                    // 机身号变了
                    if (olde.IMEINumber__c != e.IMEINumber__c && e.CombinationForm__c != null) {
                        newCombiIds.add(e.CombinationForm__c);
                    }
                }
            }
        }
        // 新的组合形式更新
        if (newCombiIds.size() > 0) {
            List<CombinationForm__c> updList = setUpdateCombiList(newCombiIds);
            update updList;
        }
        // 旧的组合形式更新
        if (oldCombiIds.size() > 0) {
            List<CombinationForm__c> updList = setUpdateCombiList(oldCombiIds);
           // update updList;
        }
    }

    /*
    仪器状态改变时，如果仪器被引用为了新资产，且引用此仪器的仪器的退换机标志是  已升级、已被加装、已联机时，仪器状态与新资产的仪器状态一致。
    **/
    public static void updateRelatedEquipment(List<Equipment__c> eList ,Map<Id,Equipment__c> oldMap ){

        Map<Id,String> eMap = new Map<Id,String>();
        for (Equipment__c e  : eList) {
            Equipment__c old = oldMap.get(e.Id);
            if(old == null)continue;
            if(old.OpponentStatus__c != e.OpponentStatus__c ){
                 eMap.put(e.Id,e.OpponentStatus__c);
                 
            }
           
        }
        if(eMap.isEmpty())return;

        List<Equipment__c> uLi = new List<Equipment__c>();
        for(Equipment__c e : [select Id ,Instrument__c from Equipment__c  where Instrument__c in:eMap.keySet() and type__c in ('已升级','已被加装','已联机')  ]){
            if(eMap.containsKey(e.Instrument__c)){
                e.OpponentStatus__c = eMap.get(e.Instrument__c);
                uLi.add(e);
            }
        }
        if(!uLi.isEmpty())update uLi;

    }

    //组合形式的状态变化 去更新相关仪器的状态
    public static void updateEquipmentStutas(List<CombinationForm__c> list_new , Map<Id,CombinationForm__c> oldMap){

        Map<Id,CombinationForm__c> eMap = new Map<Id,CombinationForm__c>();
        for (CombinationForm__c c  : list_new) {

             CombinationForm__c old = oldMap.get(c.Id);
            if(old == null)continue;
            if(old.OpponentStatus__c != c.OpponentStatus__c ){
                 eMap.put(c.Id,c);
                 
            }
            
        }
        if(eMap.isEmpty())return ;
        List<Equipment__c> uLi = new List<Equipment__c>();
        for (Equipment__c e  :[select Id,CombinationForm__c from Equipment__c where CombinationForm__c in:eMap.keySet()] ) {
           e.OpponentStatus__c = eMap.get(e.CombinationForm__c).OpponentStatus__c;
           e.DutyOfficer__c = eMap.get(e.CombinationForm__c).DutyOfficer__c;
            uLi.add(e);
        }
        if(!uLi.isEmpty())update uLi;
    }

    private static List<CombinationForm__c> setUpdateCombiList(Set<Id> ids) {
        List<Equipment__c> eList = [select Id, IMEINumber__c, CombinationForm__c, Product__r.Model__c from Equipment__c where CombinationForm__c in :ids];
        Map<Id, List<Equipment__c>> combiEquipMap = new Map<Id, List<Equipment__c>>();
        for (Equipment__c e : eList) {
            List<Equipment__c> tmp = new List<Equipment__c>();
            if (combiEquipMap.containsKey(e.CombinationForm__c)) {
                tmp = combiEquipMap.get(e.CombinationForm__c);
            }
            tmp.add(e);
            combiEquipMap.put(e.CombinationForm__c, tmp);
        }
        List<CombinationForm__c> updList = new List<CombinationForm__c>();
        for (Id id : ids) {
            CombinationForm__c cf = new CombinationForm__c(Id = id);
            String str = '';
            if (combiEquipMap.containsKey(id)) {
                for (Equipment__c e : combiEquipMap.get(id)) {
                    str += (String.isBlank(e.Product__r.Model__c) ? '' : e.Product__r.Model__c) + '(' + (String.isBlank(e.IMEINumber__c) ? '' : e.IMEINumber__c) + ')-';
                }
            }
            if (str != '') str = str.substring(0, str.length() - 1);
            cf.LinkedEquip__c = str;

            updList.add(cf);
        }

        return updList;
    }
    /*
        仪器生成后发任务给发货申请上公司的财务。
        仪器财务在仪器上点击“确认保修条款”的按钮，带出保修条款，确认后，仪器上的保修条款标记为已确认。
        确认后财务不可能修改仪器上的保修条款。确认之前财务可以修改仪器上的保修条款。


   
     public  static void  sendTask( List<Equipment__c> list_new){
        //仪器id,安装申请id 
        Map<Id,Id >  eqMap= new Map<Id,Id >();

        for (Equipment__c e :list_new ) {
            if(e.RelatedInstallationApplication__c != null )eqMap.put(e.Id , e.RelatedInstallationApplication__c);
        }
        if(eqMap.isEmpty())return;
        //所有人对应的公司
        Map<Id,String> eqCompany = new Map<Id,String>();

        for(InstallationApply__c ia : [select Id,OwnerId from InstallationApply__c where Id in: eqMap.values()]){
            
            eqCompany.put(ia.Id , ia.OwnerId  );
        }

        Map<Id,String>uComMap = new Map<Id,String>();
        for (User u  :[select Id ,SubCompany__c from User where Id in: eqCompany.values() ] ) {
            uComMap.put(u.Id,u.SubCompany__c);  
        }


        //财务
        Map<String,Id> fMap = new Map<String,Id>();
        for(UserInformation__c uinfo :[select Id ,SubCompany__c ,FinancialManager__c 
            from UserInformation__c where  SubCompany__c in:uComMap.values()]){
            if(uinfo.FinancialManager__c != null )fMap.put(uinfo.SubCompany__c, uinfo.FinancialManager__c);
        }
        
        List<Task> tList = new List<Task>();
        for ( Id eid: eqMap.keySet() ) {
            
            Task t = new Task();
            t.WhatId = eid;
            try {
              t.OwnerId = fMap.get(uComMap.get(eqCompany.get(eqMap.get(eid) ) ) ); 
            }
            catch (Exception e) {
                continue;
            }
            t.Subject = '请确认此仪器的保修信息后关闭此任务！';
            t.Description = t.Subject;
            t.ActivityDate = System.today();
            t.Priority = 'Normal';
            tList.add(t);
            
        
        }
        if(!tList.isEmpty())insert tList;


     }
      */
/*
发给销售助理的通知：XX客户有新的仪器生成，请及时关注！如果是非正常销售仪器请关联“合作标准”，完成之后可关闭此任务！

发给财务会计的通知：XX客户有新的仪器生成，请及时关注！如果是非正常销售仪器请在仪器上补充“仪器集团投放成本“，并在任务量追踪表中维护“已收保证金金额(万元)”和“已收费用金额(租赁/维保/服务费-万元）”，完成之后可关闭此任务！
*/
    //仪器新建之后 发通知给财务和销售助理
    /*public static void  sendTask(List<Equipment__c> list_new){
        Set<Id>  eqSet= new Set<Id>();
        for (Equipment__c e :list_new ) {
            eqSet.add(e.Id);
        }
        List<Task> tList = new List<Task>();
        Map<Id,Id> financeMap  = new Map<Id,Id>();
        Map<Id,Equipment__c> eMap = new Map<Id,Equipment__c>();
        for(Equipment__c eq :[select Id, EnterWay__c ,Account__r.Name,RelatedWorkOrders__r.WorkOrderInstallApplication__r.OwnerId from Equipment__c where Id in:eqSet ]){
           if(eq.RelatedWorkOrders__r.WorkOrderInstallApplication__r.OwnerId != null ){
                financeMap.put(eq.Id, eq.RelatedWorkOrders__r.WorkOrderInstallApplication__r.OwnerId);
                eMap.put(eq.Id, eq);
            }

           // Task t2 = new Task();
           //  t2.OwnerId = Id.valueOf(System.Label.Assitant);
           //  t2.WhatId = eq.Id;
           //  t2.Description  = eq.Account__r.Name +'有新的仪器生成，请及时关注！如果是非正常销售仪器请关联“合作标准”，完成之后可关闭此任务！';
           //  t2.Priority = 'Normal';
           //  t2.Subject = eq.Account__r.Name +'有新的仪器生成，请及时关注！如果是非正常销售仪器请关联“合作标准”，完成之后可关闭此任务！';
           //  t2.ActivityDate = Date.valueOf(System.now()).addDays(1);
           //  tList.add(t2);
        }
        Map<Id,User>  userMap = new Map<Id,User>();
        for(User u :[select Id,FinancialCenterManager__c from User where Id in: financeMap.values() and isActive = true]){
            userMap.put(u.Id,u);
        }
        Map<String,List<String>> ssMap = new Map<String,List<String>>();
        Set<String>  ns = new Set<String>();
        for(String sub : System.Label.Assitant.split(';',-1)){
            List<String> ss = sub.split('-',-1);
            ssMap.put(ss[0], ss);
            if(ss.size() > 1)ns.add(ss[1]);
           
        }
        Map<String ,Id> uMap = new Map<String,Id>();
        for (User u :[select Id ,Name from User where Name in:ns and isActive = true] ) {
            uMap.put(u.Name,u.Id );
        }

        for (Equipment__c e :eMap.values() ) {
            if(e.EnterWay__c == '正常销售') continue;
            //只有正常销售的才发通知
            if(financeMap.containsKey(e.Id) && userMap.containsKey(financeMap.get(e.Id))){

               // 发给财务主管的任务变更成：XXXX有新的仪器生成，请及时完善仪器的子公司成本和进入方式，完成后可关闭任务！
              // 文明红  15:48:41
               // 邹欣均，唐汇桢，财务主管

                 Task t1 = new Task();
                t1.OwnerId = userMap.get(financeMap.get(e.Id)).FinancialCenterManager__c;
                t1.WhatId = e.Id;
                t1.Description  = e.Account__r.Name +ssMap.get('财务主管').get(2);
                t1.Priority = 'Normal';
                t1.ActivityDate = Date.valueOf(System.now()).addDays(1);
                t1.Subject = e.Account__r.Name +ssMap.get('财务主管').get(2);
                if(t1.OwnerId != null )tList.add(t1);

                Task t2 = new Task();
                t2.OwnerId = uMap.get(ssMap.get('销售助理').get(1));
                t2.WhatId = e.Id;
                t2.Description  = e.Account__r.Name +ssMap.get('销售助理').get(2);
                t2.Priority = 'Normal';
                t2.Subject = e.Account__r.Name +ssMap.get('销售助理').get(2);
                t2.ActivityDate = Date.valueOf(System.now()).addDays(1);
                if(uMap.get(ssMap.get('销售助理').get(1)) != null )tList.add(t2);

                Task t3 = new Task();
                t3.OwnerId = uMap.get(ssMap.get('集团财务').get(1));
                t3.WhatId = e.Id;
                t3.Description  = e.Account__r.Name +ssMap.get('集团财务').get(2);
                t3.Priority = 'Normal';
                t3.Subject = e.Account__r.Name +ssMap.get('集团财务').get(2);
                t3.ActivityDate = Date.valueOf(System.now()).addDays(1);
                if(uMap.get(ssMap.get('集团财务').get(1)) != null )tList.add(t3);

            }
        }
        System.debug('==>'+tList);
        if(tList.size() > 0)insert tList;


    }*/
}